package org.onvivals.app.task;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.app.ai.llm.LLMFactory;
import org.onvivals.app.mqtt.util.PlayUtil;
import org.onvivals.module.iot.entity.IotDevice;
import org.onvivals.module.iot.service.IIotDeviceService;
import org.onvivals.module.pms.entity.PmsHistory;
import org.onvivals.module.pms.entity.PmsRole;
import org.onvivals.module.pms.entity.PmsRoleIndividuality;
import org.onvivals.module.pms.service.IPmsHistoryService;
import org.onvivals.module.pms.service.IPmsRoleIndividualityService;
import org.onvivals.module.pms.service.IPmsRoleService;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.entity.UmsUserRole;
import org.onvivals.module.ums.service.IUmsUserRoleService;
import org.onvivals.module.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
@Slf4j
public class DeviceTask {

	@Autowired
	private IIotDeviceService deviceService;

	@Autowired
	private IPmsHistoryService pmsHistoryService;

	@Scheduled(cron = "0 0/1 * * * ?")
	public void task() {
		System.out.println("task");

		// 获取当前的小时和分钟
		LocalDateTime now = LocalDateTime.now();
		int currentHour = now.getHour();
		int currentMinute = now.getMinute();

		// 查询状态为 3 且 Time 不为空的设备
		List<IotDevice> list = deviceService.list(
				Wrappers.<IotDevice>lambdaQuery()
						.eq(IotDevice::getStatus, 3)
						.isNotNull(IotDevice::getTime)
		);

		// 遍历设备列表
		Random random = new Random();
		// 遍历设备列表
		for (IotDevice device : list) {
			String timeStr = device.getTime(); // 假设 `Time` 是存储时间的字段，格式为 "HH:mm"
			try {
				LocalTime deviceTime = LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm"));
				// 比较设备时间和当前时间
				if (deviceTime.getHour() == currentHour && deviceTime.getMinute() == currentMinute) {
					pmsHistoryService.remove(Wrappers.<PmsHistory>lambdaQuery().eq(PmsHistory::getDeviceId,device.getSerialNumber()));
					String message = random.nextBoolean() ? "coze1" : "coze2";
					executeTaskForDevice(device, message);
				}
			} catch (DateTimeParseException e) {
				System.err.println("时间解析失败: " + timeStr);
			}
		}
	}

	@Async
	public void executeTaskForDevice(IotDevice device ,String message) {
		System.out.println("执行任务 for device: " + device.getSerialNumber());
		// 给大模型发送消息
		processDeviceMessage(device, message);
	}

	public void processDeviceMessage(IotDevice iotDevice, String responseText) {
		String deviceNum = iotDevice.getSerialNumber();
		Long userId = iotDevice.getUserId();
		if (ObjectUtil.isEmpty(userId)) {
			log.warn("设备未绑定用户: {}", deviceNum);
			return;
		}
		IUmsUserService iUmsUserService = SpringUtil.getBean(IUmsUserService.class);
		UmsUser umsUser = iUmsUserService.getById(userId);

		// 检查用户会员状态
		if (ObjectUtil.isNotEmpty(umsUser)) {
			Date vipExpireTime = umsUser.getVipExpireTime();
			if (ObjectUtil.isNotEmpty(vipExpireTime) && vipExpireTime.before(new Date())) {
				PlayUtil playUtil = SpringUtil.getBean(PlayUtil.class);
				// 播放会员过期提示音
				playUtil.play(deviceNum, "http://101.126.138.204:9000/toy/toy/no_money.MP3", "0", 99);
				log.warn("用户会员已过期: {}", deviceNum);
				return;
			}
		}
		// 获取设备角色
		IPmsRoleService iPmsRoleService = SpringUtil.getBean(IPmsRoleService.class);
		PmsRole pmsRole = ObjectUtil.isNotEmpty(iotDevice.getRoleId()) ?
				iPmsRoleService.getById(iotDevice.getRoleId()) :
				iPmsRoleService.getOne(Wrappers.<PmsRole>lambdaQuery().eq(PmsRole::getIsDefault, true));
		if (pmsRole == null) {
			log.warn("未找到角色信息: {}", deviceNum);
			return;
		}
		log.info("角色 :{}", pmsRole.getName());

		// 获取角色个性化设置
		IPmsRoleIndividualityService iPmsRoleIndividualityService = SpringUtil.getBean(IPmsRoleIndividualityService.class);
		PmsRoleIndividuality roleIndividuality = iPmsRoleIndividualityService.getById(iotDevice.getIndividualityId());
		if (roleIndividuality != null) {
			String prompt = roleIndividuality.getPrompt();
			if (StrUtil.isNotEmpty(prompt) && umsUser != null) {
				prompt = replacePlaceholders(prompt, umsUser, pmsRole, userId);
				if (StrUtil.isNotEmpty(iotDevice.getContent())) {
					prompt = prompt.replace("{{note}}", iotDevice.getContent());
				}
				pmsRole.setPrompt(prompt);
			}
		}

		// 调用聊天逻辑
		LLMFactory.build(pmsRole).chat(responseText, deviceNum, deviceNum);
	}

	private String replacePlaceholders(String prompt, UmsUser umsUser, PmsRole pmsRole, Long userId) {
		if (StrUtil.isNotEmpty(umsUser.getNickname())) {
			prompt = prompt.replace("{{nickname}}", umsUser.getNickname());
		}
		if (StrUtil.isNotEmpty(umsUser.getGender())) {
			prompt = prompt.replace("{{sex}}", umsUser.getGender());
		}
		if (StrUtil.isNotEmpty(umsUser.getBirthday())) {
			prompt = prompt.replace("{{birthday}}", umsUser.getBirthday());
		}
		if (StrUtil.isNotEmpty(umsUser.getIntroduction())) {
			prompt = prompt.replace("{{Introduction}}", umsUser.getIntroduction());
		}

		IUmsUserRoleService iUmsUserRoleService = SpringUtil.getBean(IUmsUserRoleService.class);
		UmsUserRole userRole = iUmsUserRoleService.getOne(Wrappers.<UmsUserRole>lambdaQuery()
				.eq(UmsUserRole::getUserId, userId)
				.eq(UmsUserRole::getRoleId, pmsRole.getId()));
		if (ObjectUtil.isNotEmpty(userRole)) {
			prompt = prompt.replace("{{botname}}", userRole.getRoleName());
		}
		log.info("提示词: {}", prompt);
		return prompt;
	}
}
